package aliyun.cx.admin.controller;

import aliyun.cx.admin.entity.Category;
import aliyun.cx.admin.service.CategoryService;
import aliyun.cx.admin.util.ConfigUtil;
import aliyun.cx.common.util.ResponseUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 分类管理控制器
 */
@RestController
@RequestMapping("/api/admin/categories")
@CrossOrigin(origins = "*", maxAge = 3600)
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    @Autowired
    private ConfigUtil configUtil;
    
    /**
     * 获取分类列表（分页）
     */
    @GetMapping
    public Map<String, Object> getCategoryList(@RequestParam(defaultValue = "1") Integer current,
                                              @RequestParam(defaultValue = "10") Integer size,
                                              @RequestParam(required = false) String name) {
        try {
            Page<Category> page = categoryService.getCategoryPage(current, size, name);
            return ResponseUtil.success(page);
        } catch (Exception e) {
            return ResponseUtil.error("获取分类列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有分类列表（不分页）
     */
    @GetMapping("/all")
    public Map<String, Object> getAllCategories() {
        try {
            List<Category> categories = categoryService.getAllCategories();
            return ResponseUtil.success(categories);
        } catch (Exception e) {
            return ResponseUtil.error("获取分类列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取分类
     */
    @GetMapping("/{id}")
    public Map<String, Object> getCategoryById(@PathVariable Long id) {
        try {
            Category category = categoryService.getById(id);
            if (category != null) {
                return ResponseUtil.success(category);
            } else {
                return ResponseUtil.error(404, "分类不存在");
            }
        } catch (Exception e) {
            return ResponseUtil.error("获取分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建分类
     */
    @PostMapping
    public Map<String, Object> createCategory(@RequestBody Category category) {
        try {
            // 检查分类创建功能是否启用
            if (!configUtil.isCategoryCreateEnabled()) {
                return ResponseUtil.error(403, "分类创建功能已禁用");
            }
            
            // 验证分类名称
            if (category.getName() == null || category.getName().trim().isEmpty()) {
                return ResponseUtil.error(400, "分类名称不能为空");
            }
            
            if (category.getName().length() > 50) {
                return ResponseUtil.error(400, "分类名称不能超过50个字符");
            }
            
            String categoryName = category.getName().trim();
            
            // 检查分类名称是否已存在（包括已删除的分类）
            if (categoryService.isNameExists(categoryName, null) || categoryService.findDeletedCategoryByName(categoryName) != null) {
                return ResponseUtil.error(400, "分类名称已存在，请使用其他名称");
            }
            
            boolean success = categoryService.createCategory(category);
            return ResponseUtil.crudResult(success, "创建", category);
        } catch (Exception e) {
            return ResponseUtil.error("创建分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新分类
     */
    @PutMapping("/{id}")
    public Map<String, Object> updateCategory(@PathVariable Long id, @RequestBody Category category) {
        try {
            // 验证分类名称
            if (category.getName() == null || category.getName().trim().isEmpty()) {
                return ResponseUtil.error(400, "分类名称不能为空");
            }
            
            if (category.getName().length() > 50) {
                return ResponseUtil.error(400, "分类名称不能超过50个字符");
            }
            
            // 检查分类名称是否已存在（排除当前分类）
            if (categoryService.isNameExists(category.getName().trim(), id)) {
                return ResponseUtil.error(400, "分类名称已存在");
            }
            
            category.setId(id);
            boolean success = categoryService.updateCategory(category);
            return ResponseUtil.crudResult(success, "更新", category);
        } catch (Exception e) {
            return ResponseUtil.error("更新分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除分类（软删除）
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteCategory(@PathVariable Long id) {
        try {
            // 检查分类是否被文章使用
            if (categoryService.isCategoryInUse(id)) {
                return ResponseUtil.error(400, "该分类下有文章，无法删除");
            }
            
            boolean success = categoryService.softDeleteCategory(id);
            return ResponseUtil.crudResult(success, "删除", null);
        } catch (Exception e) {
            return ResponseUtil.error("删除分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 恢复已删除的分类
     */
    @PutMapping("/{id}/restore")
    public Map<String, Object> restoreCategory(@PathVariable Long id) {
        try {
            boolean success = categoryService.restoreCategory(id);
            return ResponseUtil.crudResult(success, "恢复", null);
        } catch (Exception e) {
            return ResponseUtil.error("恢复分类失败：" + e.getMessage());
        }
    }
}
